﻿using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Web.UI.WebControls;
using SMIL.Server.PictureLibraryExif;

namespace SMIL.Server.PictureLibraryExif.Layouts
//namespace SMIL.Server.PictureLibraryExif
{
    public partial class SMILPictureLibraryExifSettingsPage : LayoutsPageBase
    {
        private const string assembly = "SMIL.Server.PictureLibraryExif, Version=1.0.0.0, Culture=neutral, PublicKeyToken=04f2cc173fa3cc5e";
        private const string receiver = "SMIL.Server.PictureLibraryExif.PictureLibraryExif";
        private readonly Guid _FeatureID = new Guid("4660fddc-954c-442f-926d-da93a6519837");
        private readonly Version _Version = new Version(1, 0, 0, 0);
        protected Label LabelErrorMessage;
        protected Button BtnSave;
        protected CheckBox UseExifData;
        protected InputFormSection useExif;
        protected Label CurrentVersion;
        protected Label LatestVersion;
        protected Button CheckLatestVersion;
        protected SPList List;

        protected void Page_Load(Object sender, EventArgs e)
        {
            string[] query = Request.QueryString.GetValues("list");
            #region verify query string
            if (query == null || query.Length < 1)
            {
                ShowError("Please call this page from the Settings Menu within a list.");
                useExif.Visible = false;
                return;
            }
            #endregion

            try
            {
                List = Common.GetList(SPContext.Current.Web, new Guid(query[0]));

                #region check if user has rights
                if (!List.DoesUserHavePermissions(SPBasePermissions.ManageLists))
                {
                    ShowError("You do not have the right to manage lists.");
                    useExif.Visible = false;
                    return;
                }
                #endregion

                if (List != null)
                {
                    #region check if feature is activated for this spweb
                    if (!Common.FeatureActivated(SPContext.Current.Web, _FeatureID))
                    {
                        ShowError("The feature \"SMIL.Server.PictureLibraryExif\" is not activated for the current web.");
                        useExif.Visible = false;
                        return;
                    }
                    #endregion

                    if (!Page.IsPostBack)
                    {
                        var eventReceiver = Common.GetEventReceiver(List.EventReceivers, receiver);
                        if (eventReceiver != null)
                        {
                            UseExifData.Checked = true;
                        }

                        CurrentVersion.Text = string.Format("Current Version: {0}<br/>", _Version);
                        LatestVersion.Text = "Latest Version:<br/>";
                    }
                }
            }
            catch (Exception ex)
            {
                throw new SPException(ex.ToString());
            }
        }

        protected void CheckLatestVersion_Click(object sender, EventArgs e)
        {
            try
            {               

            }
            catch (Exception ex)
            {
                throw new SPException(ex.Message);
            }
        }

        public void BtnSave_Click(Object sender, EventArgs e)
        {
            try
            {
                string webUrl = SPContext.Current.Web.Url;
                var systemUser = GetUser(@"SHAREPOINT\SYSTEM");
                var systemToken = systemUser.UserToken;

                using (var site = new SPSite(webUrl, systemToken))
                using (var web = site.OpenWeb())
                {
                    var allowUnsafeUpdates = web.AllowUnsafeUpdates;
                    web.AllowUnsafeUpdates = true;

                    var list = web.Lists[List.ID];

                    // add handler if necessary
                    var eventReceiver = Common.GetEventReceiver(List.EventReceivers, receiver);
                    if (UseExifData.Checked)
                    {
                        if (eventReceiver == null)
                        {
                            list.EventReceivers.Add(SPEventReceiverType.ItemAdded, assembly, receiver);
                        }
                    }
                    else
                    {
                        // remove the handler
                        if (eventReceiver != null)
                        {
                            eventReceiver.Delete();
                        }
                    }

                    web.AllowUnsafeUpdates = allowUnsafeUpdates;
                }

                // redirect
                Redirect();
            }
            catch (Exception ex)
            {
                throw new SPException(ex.ToString());
            }
        }

        /// <summary>
        /// shows an error and hides people fields an submit button
        /// </summary>
        /// <param name="errorMessage"></param>
        internal void ShowError(string errorMessage)
        {
            LabelErrorMessage.Text = string.Format("<strong>{0}</strong><br/><br/>", errorMessage);
            UseExifData.Visible = false;
            BtnSave.Visible = false;
        }

        private static SPUser GetUser(string loginName)
        {
            var webUrl = SPContext.Current.Site.Url;
            SPUser user = null;
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate
                                                         {
                                                             using (var site = new SPSite(webUrl))
                                                             using (var rootWeb = site.RootWeb)
                                                             {
                                                                 //TODO Testen wenn serviceaccount noch nicht angeleldet war
                                                                 user = Common.GetCurrentUser(rootWeb);
                                                             }
                                                         });
            }
            catch (Exception ex)
            {
                Common.WriteULSError(string.Format("Error getting the account '{0}': {1}", loginName, ex));
            }
            return user;
        }

        private void Redirect()
        {
            if (List != null)
            {
                var url = string.Format("{0}/_layouts/listedit.aspx?List={1}", SPContext.Current.Web.Url, List.ID);
                Response.Redirect(url);
            }
            else
            {
                Response.Redirect(SPContext.Current.Web.Url);
            }

        }
    }
}
